const express = require('express')
const mysql = require('mysql');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const secret = 'oner';
const cryptoHmac = (datas) => crypto.createHmac('sha256', secret).update(datas).digest('hex');
const app = express()
const config = require('./config/index')
const conn = require('./config/dbconfig');
const connection = mysql.createConnection(conn);
connection.connect();

app.use('/static', express.static('public'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.post('/setnum', (req,res)=>{
    let data = req.body;
    let sqlStr =  `update qx_shopcart set num=${data.num} where username='${data.username}' and pro_id=${data.id} and status=1`;
    connection.query(sqlStr, (err, resultes, fields) => {
        if(err){
            res.send({
                msg : err,
                status : -1,
            });
        }
        res.send({
            msg : 'success',
            status : 1,
        });
    });
});

app.post('/addshop', (req, res) => {
    let data = req.body;
    connection.query(`select * from qx_shopcart where pro_id=${data.id}`, (err, resultes, fields) => {
        if (err) {
            res.send({
                msg: err,
                status: -1,
            });
        }
        if (resultes.length > 0) {
            let num = ++resultes[0].num;
            let pro_id = resultes[0].pro_id;
            let username = resultes[0].username;
            let status = resultes[0].status;
            let sqlStr = `UPDATE qx_shopcart set num=${num} where pro_id=${pro_id} and username='${username}' and status=${status}`;
            connection.query(sqlStr, (err, results, fields) => {
                if (err) {
                    res.send({
                        msg: err,
                        status: -1,
                    });
                }
                res.send({
                    msg: 'success',
                    status: 1,
                });
            });
        } else {
            let num = 1;
            let tim = new Date().getTime();
            let sqlStr = `INSERT INTO qx_shopcart (username,pro_id,num,addtime) values
            ('${data.username}',${data.id},${num},'${tim}')`;
            connection.query(sqlStr, (err, results, fields) => {
                if (err) {
                    res.send({
                        msg: err,
                        status: -1,
                    });
                }
                res.send({
                    msg: 'success',
                    status: 1,
                });
            });
        }
    });
});

app.post('/register', (req, res) => {
    let data = req.body;
    let psw = cryptoHmac(data.password);
    let sqlStr = `insert into qx_users (username,password) values("${data.username}","${psw}")`;
    connection.query(sqlStr, (err, results, fields) => {
        if (err) {
            res.json({
                msg: 'register error.'
            });
            throw err;
        }
        res.json({
            msg: `register success ${fields}`
        });
    });
});

app.post('/login', (req, res) => {
    let data = req.body;
    let sqlStr = `select * from qx_users where username = ${data.username}`;
    connection.query(sqlStr, (err, results, fields) => {
        if (err) {
            res.send({
                msg: 'query error',
                status: -1,
            });
        }
        if (results.length < 1) {
            res.send({
                msg: `${data.username} 未注册`,
                status: 0,
            });
        }
        if (results[0].password !== cryptoHmac(data.password)) {
            res.send({
                msg: '密码错误！',
                a: results[0].password,
                b: cryptoHmac(data.password),
                status: 2,
            });
        }

        let cookieStr = JSON.stringify({ user: data.username })
        res.cookie('loginCookie', cookieStr, { maxAge: 18000000 });
        res.cookie('loginA', data.username, { maxAge: 600000 });
        res.cookie('loginB', data.username, { maxAge: 600000 });
        res.cookie('loginC', data.username, { maxAge: 600000 });
        res.cookie('loginD', data.username, { maxAge: 600000 });
        res.send({
            msg: '登录成功！',
            status: 1,
        });
    })
});

app.get('/shopcart', (req, res) => {
    let data = req.query;
    let sqlStr = `select p.*,s.num,s.ischecked from qx_shopcart as s join qx_product as p on s.pro_id=p.id and s.username='${data.username}' and s.status=1`;
    // let sqlStr = `select * from qx_shopcart where username='${data.username}' and status=1`;
    connection.query(sqlStr, (err, resultes, fields) => {
        if (err) {
            res.send({
                msg: err,
                status: -1,
            });
        }
        res.send(resultes);
    });
});

app.get('/product', (req, res) => {
    let data = req.query;
    let num = data.num;
    let sqlStr = `select * from qx_product where status=1 limit 0,${num}`;
    connection.query(sqlStr, (err, results, fields) => {
        if (err) {
            res.send({
                msg: err,
                status: -1,
            });
        }
        res.send(results);
    });
});

app.get('/prodetails', (req, res) => {
    let data = req.query;
    let id = data.id;
    let sqlStr = `select * from qx_product where status=1 and id=${id}`;
    connection.query(sqlStr, (err, results, fields) => {
        if (err) {
            res.send({
                msg: err,
                status: -1,
            });
        }
        res.send(results);
    });
});

app.get('/add', (req, res) => {
    for (let i = 1; i < 50; i++) {
        let title = `${i}--防爆瑜伽球普拉提球健身球加厚防爆正品瘦身平衡瑜伽球`;
        let price = Math.trunc(Math.random() * (500 - 100) + 100);
        let oldPrice = price + Math.trunc(Math.random() * (100 - 50) + 50);
        let sales = Math.trunc(Math.random() * (3000 - 50) + 50);
        let now = new Date().getTime() + 100;

        let sqlStr = `INSERT INTO qx_product (title,img_src,price,old_price, sales, add_time)
                    values('${title}','../img/prolist1.png','${price}', '${oldPrice}','${sales}',
                    '${now}')`;
        connection.query(sqlStr, (err, results, fields) => { });
    }
});
app.listen(config.port, config.host, () => {
    console.log(`b2c-app project server start at http://${config.host}:${config.port}`)
})